package com.microservices.yucloud.api;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author zy
 * @date 2019/10/11 7:50 下午
 * 游客通过检票口
 **/
public class SemaphoreDemo {

    // 线程限流 5个检票口
    private static Semaphore semaphore = new Semaphore(5, true);

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);
        // 10个学生
        for (int i = 0; i < 10; i++) {
            service.execute(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + " 游客想要通过检票口...");
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + " 游客通过中...");
                    TimeUnit.MILLISECONDS.sleep(3000);
                    System.out.println(Thread.currentThread().getName() + " 游客通过完毕，进入园区。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release();
                }
            });
        }
        service.shutdown();
    }
}
